package com.qf.controller;


import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.service.DtsPermissionService;
import com.qf.service.DtsRoleService;
import com.qf.util.*;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/admin/auth")
public class AdminAuthController {
    @Autowired
    DtsRoleService roleService;

    @Autowired
    DtsPermissionService permissionService;

    @GetMapping("/info")
    public Object info() {
//        //获取当前登陆的主体
//        Subject subject = SecurityUtils.getSubject();
//        //从session中获取用户对象
//        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();
//        String username = admin.getUsername();
//        String avatar = admin.getAvatar();
//        Integer[] roleIds = admin.getRoleIds();
//        Set<String> rolesByRoleIds = roleService.findRolesByRoleIds(roleIds);
//        Set<String> permsByRoleIds = permissionService.findPermsByRoleIds(roleIds);
//
//        //封装的返回值对象
//        Map<String, Object> data = new HashMap<>();
//        data.put("name", username);
//        data.put("avatar", avatar);
//        data.put("roles", rolesByRoleIds);
//        data.put("perms", permsByRoleIds);
//        return ResponseUtil.ok(data);
        //获取 当前登录对象的主体
        Subject subject = SecurityUtils.getSubject();
        // 从session中 获取 用户对象（realm认证方法中返回的对象）
        DtsAdmin admin = (DtsAdmin) subject.getPrincipal();

        String username = admin.getUsername();
        String avatar = admin.getAvatar();
        Integer[] roleIds = admin.getRoleIds();
        Set<String> roles = roleService.findRolesByRoleIds(roleIds);
        Set<String> perms = permissionService.findPermsByRoleIds(roleIds);

        //封装返回值对象
        Map<String,Object> data = new HashMap<>();
        data.put("name", username);
        data.put("avatar", avatar);
        data.put("roles", roles);
        data.put("perms", perms);

        return ResponseUtil.ok(data);
    }

    @PostMapping("/login")
    public Object login(@RequestBody Map<String, String> params) {
        //获取前端数据
        String code = params.get("code");
        String username = params.get("username");
        String password = params.get("password");
        String uuid = params.get("uuid");

        //验证验证码
        //从缓存中取出来
        String cacheCode = CaptchaCodeManager.getCachedCaptcha(uuid);
        //判断验证码是否正确
        if (StringUtils.isEmpty(code) || !code.equalsIgnoreCase(cacheCode)) {
            System.out.println("校验失败");
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_EXPIRED);
        }
        //判断用户名或者密码是否为空
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return ResponseUtil.badArgument();
        }
        //shiro框架 完成认证和授权
        Subject subject = SecurityUtils.getSubject();
        //创建token
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //登陆
        try {
            subject.login(token);
            System.out.println("超级管理员角色：" + subject.hasRole("超级管理员"));
            System.out.println("品牌列表展示权限：" + subject.isPermitted("admin:brand:list"));
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_UNKOWN_ACCOUNT);
        } catch (LockedAccountException e) {
            e.printStackTrace();
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_LOCK_ACCOUNT);
        } catch (CredentialsException e) {
            e.printStackTrace();
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_AUTH);
        }

        return ResponseUtil.ok(subject.getSession().getId());


    }

    @GetMapping("/captchaImage")
    public Object captchaImage() throws IOException {
        //生成验证码
        String verifyCode = VerifyCodeUtils.generateVerifyCode(1);
        //生成随机数
        String uuid = UUID.randomUUID().toString();
        CaptchaCodeManager.addToCache(uuid, verifyCode, 5);
        //存在服务端
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        //生成验证码图片
        VerifyCodeUtils.outputImage(120, 40, outputStream, verifyCode);
        //创建返回值数据
        Map<String, Object> data = new HashMap<>();
        data.put("img", Base64.encode(outputStream.toByteArray()));
        data.put("uuid", uuid);
        return ResponseUtil.ok(data);
    }

}
